import axios from 'axios'
import router from "../router";
import store from "../store";
import { Message } from 'element-ui';
import {addErrorLog} from "./api";
import qs from "qs";
//1. 创建新的axios实例，
const _axios = axios.create({
    baseURL: process.env.VUE_APP_URL,
})

_axios.interceptors.request.use(require=>{
    /*如果缓存中userToken不为空，那么每次请求就把token带上*/
    if(localStorage.getItem("userToken")){
        require.headers.userAuth = localStorage.getItem("userToken")
    }
    require.headers.timestamp=Math.round(new Date().getTime() / 1000);
    return require
},error=>{
    return Promise.reject(error);
})


_axios.interceptors.response.use(response=>{
    if(response.data.status===999){
        addErrorLog(qs.stringify({uid:store.state.userid,err:JSON.stringify(response.data)}))
    }
    if(response.status===200 && response.data.token){
        localStorage.setItem('userToken',response.data.token) //将token存入缓存中
    }
    if(response.data.status===119){
        localStorage.setItem('href',location.href)//登录过期 记录当前地址
        localStorage.removeItem("userToken");
        store.commit('setDlzt');
        router.push("/login");
    }else if(response.data.status===299){
        Message.error("权限不足")
        setTimeout(()=>{
            router.go(-1)
            router.replace("/")
        },3000)
    }
    return response.data
},error=>{

    return Promise.reject(error)
})


export default _axios
